<template>
    <div class="search">
        <input type="text" placeholder="请输入要查询的城市" v-model="keyWords">
        <div class="search-content" v-show="show" ref="wrapper">
            <div>
                <div class="item border-bottom" v-for="item in resultList" :key="item.id"
                @click="change(item.name)">
                {{item.name}}
                </div>
                <div class="tip" v-show="!showMessage">没有查询到结果</div>
            </div>
        </div>
    </div>
</template>
<script>
import BScroll from 'better-scroll'
import { mapMutations } from 'vuex'
export default {
  name: 'CitySearch',
  props: {
    cities: {
      type: Object
    },
    alphabet: {
      type: Array
    }
  },
  data () {
    return {
      keyWords: '',
      resultList: [],
      bs: null,
      timer: null
    }
  },
  computed: {
    show () {
      return this.keyWords
    },
    showMessage () {
      return this.resultList.length
    }
  },
  methods: {
    change (data) {
      this.changeCity(data)
      this.keyWords = ''
      this.$router.push('/')
    },
    ...mapMutations({
      changeCity: 'changeCity'
    })
  },
  mounted () {
    let el = this.$refs.wrapper
    this.bs = new BScroll(el, {
      click: true
    })
  },
  watch: {
    keyWords (newVal, oldValue) {
      console.log(newVal)
      if (newVal === '') {
        this.resultList = []
        return
      }
      if (this.timer) {
        this.timer = null
      }
      this.timer = setTimeout(() => {
        console.log('calculate')
        this.resultList = []
        this.alphabet.forEach((item) => {
          this.cities[item].forEach((i) => {
            if (i.spell.indexOf(newVal) !== -1) {
              this.resultList.push(i)
            }
            if (i.name.indexOf(newVal) !== -1) {
              this.resultList.push(i)
            }
          })
        })
      }, 8)
      console.log(newVal)
    }
  }
}
</script>
<style lang="stylus" scoped>
@import '~@/assets/styles/varibles.styl'
    .search
        height .72rem
        padding 0 .1rem
        background-color $bgColor
        input
            width 100%
            height .62rem
            border-radius .06rem
            color #666
            box-sizing border-box
            margin-top .05rem
            text-align center
            padding 0 .1rem
        .search-content
            height 100%
            overflow hidden
            background-color #fff
            position fixed
            top 1.58rem
            left 0
            right 0
            bottom 0
            z-index 1
            .item
                line-height .62rem
                height .62rem
                color #666
                padding-left .2rem
</style>
